package com.example.tech.folio.controller;

import com.example.tech.folio.mapper.ImageMapper;
import com.example.tech.folio.pojo.entity.Image;
import com.example.tech.folio.pojo.vo.ImageVO;
import com.example.tech.folio.web.JsonResult;
import com.example.tech.folio.web.State;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/image")
public class ImageController {

    // 静态常量
    public static final int IMAGE_TYPE_PROFILE_PHOTO = 0;
    public static final int IMAGE_TYPE_PROJECT_COVER = 1;

    @Value("${tech-folio.file.upload-dir}")
    private String uploadDir;

    @Autowired
    private ImageMapper imageMapper;

    @PostMapping("/upload")
    public JsonResult uploadImage(int imageType, MultipartFile file) {
        // 校验是否上传
        if (file == null || file.isEmpty()) {
            throw new RuntimeException(State.ERR_NOT_FOUND);
        }

        // 校验图片类型
        if (imageType != IMAGE_TYPE_PROFILE_PHOTO && imageType != IMAGE_TYPE_PROJECT_COVER) {
            throw new RuntimeException(State.ERR_CONFLICT);
        }

        // 校验文件
        if (file.isEmpty() || !isValidImageType(file) || file.getSize() > 10 * 1024 * 1024) {
            throw new RuntimeException(State.ERR_CONFLICT);
        }

        // 保存文件
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + extension;
        String imageDir = uploadDir + "/image";
        File dir = new File(imageDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = imageDir + "/" + fileName;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败");
        }

        // 创建Image对象并保存到数据库
        Image image = new Image();
        image.setImageType(imageType);
        image.setRemoteUrl("/image/" + fileName);
        image.setLocalPath(filePath);
        image.setFileSize(file.getSize());
        imageMapper.insert(image);

        // 创建并返回ImageVO
        ImageVO imageVO = new ImageVO();
        imageVO.setId(image.getId());
        imageVO.setRemoteUrl(image.getRemoteUrl());
        return JsonResult.ok(imageVO);
    }

    private boolean isValidImageType(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null && (contentType.equals("image/jpeg") || contentType.equals("image/png"));
    }
}